/**
 * addListener(event, listener, prepend)
 * removeListener(event, listener)
 * setMaxLiseners(n)
 * once(event, listener)
 * emit(type, arg1, arg2)
 */

function EventEmitter() {
  this._maxListener = 10;
  this._events = Object.create(null);
}
EventEmitter.prototype.addListener = function (type, event, prepend) {
  const eventArr = this._events[type];
  if (eventArr) {
    if (prepend) {
      eventArr.push(event);
    } else {
      eventArr.unshift(event);
    }
  } else {
    this._events[type] = [event];
  }
};
EventEmitter.prototype.removeListener = function (type, event) {
  const eventArr = this._events[type];
  if (Array.isArray(eventArr)) {
    if (!event) {
      delete this._events[type];
    } else {
      this._events[type] = eventArr.filter((_event) => _event !== event);
    }
  }
};
EventEmitter.prototype.setMaxLiseners = function (n) {
  this._maxListener = n;
};
EventEmitter.prototype.once = function (type, event) {
  const once = (...args) => {
    event.apply(this, args);
    delete this.removeListener(type, event);
  };
  this.addListener(type, once, true);
};
EventEmitter.prototype.emit = function (type, ...args) {
  if (Array.isArray(this._events[type])) {
    this._events[type].forEach(event => {
      event.apply(this, args)
    })
  }
} 

var emitter = new EventEmitter();

var onceListener = function (args) {
  console.log("我只能被执行一次", args, this);
};

var listener = function (args) {
  console.log("我是一个listener", args, this);
};

emitter.once("click", onceListener);
emitter.addListener("click", listener);

emitter.emit("click", "参数");
emitter.emit("click");

emitter.removeListener("click", listener);
emitter.emit("click");
